angular.module('HTRD_AutoConsole.A').factory('BaseServ', ['$rootScope', '$window', '$http', '$q',
  function($rootScope, $window, $http, $q) {

    $rootScope.apiRoot = 'http://106.38.67.196:8001';

    return {
      query: function(params) {
        var deferred = $q.defer();
        var token = $window.localStorage.getItem('token');
        var ajaxConfig;

        // 读本地JSON请求
        if (params.Serv) {

          if (!!(params.param && params.param['id'])) {

            // 替换 id占位符
            params.url = params.url.replace('{id}', params.param.id);
          } else {
            params.url = params.url.replace('{id}', '');
          };

          ajaxConfig = {
            method: params.method,
            url: ($rootScope.apiRoot || '') + params.url,
            params: params.param,
            beforeSend: function(request) {
              request.setRequestHeader('token', token);
            }
          };

          var formData = {};

          if (params.method !== 'GET') {

            if (params.method === 'PUT'){
              formData = $.param(params.param);
              ajaxConfig.data = formData;
              delete ajaxConfig.params;
            } else {
              formData = $.param(params.param);
              ajaxConfig.data = formData;
            }
          }
          else {
            formData = params.param;
            ajaxConfig.params = formData;
          };

          $http(ajaxConfig).success(function (ret) {
            deferred.resolve(ret);
          }).error(function (ret) {
            deferred.reject(ret);
          });
        } else {
          $.getJSON('/src/' + params.url, params.param)
            .done(function (ret) {
              deferred.resolve(ret);
            })
            .fail(function (ret) {
              deferred.reject(ret);
            })
        };

        return deferred.promise;
      }
    }
  }
]);
